import { defineComponent, h, onMounted } from "vue"
import { getValueByModel, setValueByModel } from "./../util"
import { useEditComponents, useEditComponentOptions  } from "./hooks"


export const NumberComponent = defineComponent (
    (props: CellProps) => {
        const { inputRef, visible } = useEditComponents(props)
        
        onMounted(() => useStopPreventDefaultInputNumber(inputRef.value))

        return () => h('input', {
            ref: inputRef,
            class: { 'edit-control-components': 1, visible: visible.value  },
            value: getValueByModel(props.column.dataIndex, props.record),
            onInput: (event: InputEvent) => setValueByModel(props.column.dataIndex, props.record, event?.target?.value),
            type: 'number',
        })
    },
    useEditComponentOptions()
)

/**
 * 阻止数字输入框上下键的默认加、减行为
 */
function useStopPreventDefaultInputNumber(el: HTMLElement){
    if (el.tagName !== 'INPUT' || el.getAttribute("type") !== 'number') return;

    el.addEventListener('keydown', (event) => {
        if (event?.key === 'ArrowUp' || event?.key === 'ArrowDown') {
            event?.stopPropagation();
            event?.preventDefault();
            
            document.dispatchEvent(new KeyboardEvent('keydown', event));
        }
    })
}